<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <!-- <link
  href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.0.2/css/bootstrap.min.css"
  rel="stylesheet"
/> -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
      img {
        width: 100px;
      }
      #tb tr td {
        height: 100px;
        line-height: 100px;
        font-size: 20px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <table class="table table-bordered table-hover">
        <thead>
          <tr>
            <th>选择</th>
            <th>图片</th>
            <th>商品名</th>
            <th>价格</th>
            <th>描述</th>
            <th>数量</th>
            <th>删除</th>
          </tr>
        </thead>
        <tbody id="tb"></tbody>
      </table>
    </div>
    <script>
      //如果没有本地没有uid，请先登录
      if (!localStorage.getItem("uid")) {
        alert("请先登录呗");
        history.back(0);
      }
      refreshMyCar();
      function refreshMyCar() {
        let uid = localStorage.getItem("uid");
        $.get("/carList", { uid: uid }, (res) => {
          console.log(res);
          let str = "";
          res.data.forEach((item) => {
            str += `<tr>
            <td><input type="checkbox" name="" id=""></td>
            <td><img src="${item.pimg}" /></td>
            <td>${item.pname}</td>
            <td>￥${item.pprice}</td>
            <td>${item.pdesc}</td>
            <td><input type="number" name="" id="num" min="1" value="${item.num}" onchange="changeNum('${item._id}')"></td>
            <td>
              <button class="btn btn-danger" onclick="delCarShop('${item._id}')">删除</button>
            </td>
          </tr>`;
          });
          $("#tb").html(str);
        });
      }

      //删除购物车里的商品
      function delCarShop(thisId) {
        console.log(thisId);
        $.ajax({
          url: "/delCarShop/" + thisId,
          type: "delete",
          success: function (res) {
            console.log(res);
            alert(res.msg);
            refreshMyCar();
          },
        });
      }

      //修改商品数量
      function changeNum(thisId) {
        console.log(thisId);
        let num = $("#num").val();
        $.ajax({
          url: "/changeNum",
          type: "post",
          data: {
            thisId: thisId,
            num: num,
          },
          success: function (res) {
            console.log(res);
          },
        });
      }
    </script>
  </body>
</html>
